package com.taoyibao.hongcanting.ui.mine.activity;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.view.View;

import com.taoyibao.hongcanting.R;
import com.taoyibao.hongcanting.base.activity.BaseActivityPresenter;
import com.taoyibao.hongcanting.cache.SpUtils;
import com.taoyibao.hongcanting.constant.CodeConstant;
import com.taoyibao.hongcanting.constant.NetCode;
import com.taoyibao.hongcanting.dialog.DialogCamera;
import com.taoyibao.hongcanting.dialog.DialogChooseDate;
import com.taoyibao.hongcanting.dialog.DialogChooseGender;
import com.taoyibao.hongcanting.http.DefaultTransformer;
import com.taoyibao.hongcanting.http.JsonApiWrapper;
import com.taoyibao.hongcanting.http.ProgressSubscriber;
import com.taoyibao.hongcanting.model.CompanyBaseModel;
import com.taoyibao.hongcanting.model.UserInfoModel;
import com.taoyibao.hongcanting.ui.mine.delegate.UserInfoDelegate;
import com.taoyibao.hongcanting.utils.CameraUtils;
import com.taoyibao.hongcanting.utils.CodeUtils;
import com.taoyibao.hongcanting.utils.FileUtils;
import com.taoyibao.hongcanting.utils.ToastUtils;
import com.taoyibao.hongcanting.utils.permission.MPermission;
import com.taoyibao.hongcanting.utils.permission.OnMPermissionDenied;
import com.taoyibao.hongcanting.utils.permission.OnMPermissionGranted;
import com.taoyibao.hongcanting.utils.permission.OnMPermissionNeverAskAgain;

import java.io.File;
import java.util.HashMap;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * @author TangAnna
 * @description: 个人信息
 * @date :${DATA} 11:40
 */
public class UserInfoActivity extends BaseActivityPresenter<UserInfoDelegate> implements View.OnClickListener, DialogCamera.DialogCameraInterface, DialogChooseGender.DialogGrnderInterface, DialogChooseDate.DialogChooseDateFace {

    private static final String TAG = "UserInfoActivity";
    private static final int REQUEST_CODE_NICKNAME = 100;
    private static final int REQUEST_CODE_HEAD_CAMEAR = 101;//拍照得到的回调
    private static final int REQUEST_CODE_HEAD_XIANGCE = 103;//拍照得到的回调
    private static final int REQUEST_CODE_HEAD_CROP = 104;//裁剪之后的回调
    //请求相机权限
    private static final int REQUEST_CODE_PERMISSION = 102;
    //需要申请的权限的数组
    private String[] mPermissions = {Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};

    //用户选择的选择头像的方式
    private static final int WAY_CAMREA = 0;
    private static final int WAY_ALBUM = 1;
    /**
     * 方式 0相机  1相册
     */
    private int mWay = -1;
    private CameraUtils mCameraUtils;


    @Override
    protected Class<UserInfoDelegate> getDelegateClass() {
        return UserInfoDelegate.class;
    }

    @Override
    protected void bindEvenListener() {
        super.bindEvenListener();
        viewDelegate.get(R.id.layout_userInfo_head).setOnClickListener(this);
        viewDelegate.get(R.id.layout_userInfo_nike).setOnClickListener(this);
        viewDelegate.get(R.id.layout_userInfo_verified).setOnClickListener(this);
        viewDelegate.get(R.id.layout_userInfo_gender).setOnClickListener(this);
        viewDelegate.get(R.id.layout_userInfo_birthday).setOnClickListener(this);
        mCameraUtils = new CameraUtils(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getUserInfo();
    }

    /**
     * 获取用户的个人信息
     */
    public void getUserInfo() {
        JsonApiWrapper.getApiService().userInfo(SpUtils.getToken(), SpUtils.getMemberId())
                .compose(new DefaultTransformer<CompanyBaseModel<List<UserInfoModel>>>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel<List<UserInfoModel>>>(this, true) {
                    @Override
                    public void onNext(CompanyBaseModel<List<UserInfoModel>> listCompanyBaseModel) {
                        if (listCompanyBaseModel.code == NetCode.HTTP_200) {
                            viewDelegate.setUIData(listCompanyBaseModel);
                        } else {
                            super.onNext(listCompanyBaseModel);
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.layout_userInfo_head://头像
                DialogCamera dialogCamera = new DialogCamera(this);
                dialogCamera.show(getSupportFragmentManager(), "UserInfoActivity");
                break;
            case R.id.layout_userInfo_nike://昵称
                startActivityForResult(new Intent(this, ChangeNickActivity.class), REQUEST_CODE_NICKNAME);
                break;
            case R.id.layout_userInfo_verified://实名认证
                VerifiedActivity.open(this);
                break;
            case R.id.layout_userInfo_gender://选择性别
                DialogChooseGender mDialogChooseGender = new DialogChooseGender(this);
                mDialogChooseGender.show(getSupportFragmentManager(), "TAG");
                break;
            case R.id.layout_userInfo_birthday://选择生日
                DialogChooseDate dialogChooseDate = new DialogChooseDate();
                dialogChooseDate.setChooseDateFace(this);
                dialogChooseDate.showDilaog(getSupportFragmentManager(), TAG);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_NICKNAME://返回的昵称
                    String stringExtra = data.getStringExtra(CodeConstant.CHANGE_NICKNAME);
                    if (!TextUtils.isEmpty(stringExtra)) {
                        viewDelegate.setNickname(stringExtra);
                    }
                    break;
                case REQUEST_CODE_HEAD_CAMEAR://拍照得到的头像
                    mCameraUtils.openCrop(REQUEST_CODE_HEAD_CROP, CameraUtils.DIRECTORY_PICTURE, mCameraUtils.getOriginalUri(), 1, 1, 94, 94);
                    break;
                case REQUEST_CODE_HEAD_XIANGCE://相册得到的头像
                    Uri uri = data.getData();
                    if (uri != null) {
                        mCameraUtils.openCrop(REQUEST_CODE_HEAD_CROP, CameraUtils.DIRECTORY_PICTURE, uri, 1, 1, 94, 94);
                    }
                    break;
                case REQUEST_CODE_HEAD_CROP://裁剪
                    Uri cropUri = mCameraUtils.getCropUri();
                    if (cropUri != null) {
                        upDataHead(mCameraUtils.getCropFile());
                    }
                    break;
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        MPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    //同意
    @RequiresApi(api = Build.VERSION_CODES.M)
    @OnMPermissionGranted(REQUEST_CODE_PERMISSION)
    public void onBasicPermissionSuccess() {
        if (mWay == WAY_CAMREA) {//打开相机
            mCameraUtils.openCamera(REQUEST_CODE_HEAD_CAMEAR, CameraUtils.DIRECTORY_PICTURE);
        } else if (mWay == WAY_ALBUM) {//打开相册
            mCameraUtils.openAlbum(REQUEST_CODE_HEAD_XIANGCE);
        }
    }

    //拒绝
    @OnMPermissionDenied(REQUEST_CODE_PERMISSION)
    public void onBasicPermissionFailed() {
        ToastUtils.showToast(CodeUtils.getIdString(R.string.string_hintPermission));
    }

    //不再提醒
    @OnMPermissionNeverAskAgain(REQUEST_CODE_PERMISSION)
    public void onBasicPermissionNeverAskAgain() {
        ToastUtils.showToast(CodeUtils.getIdString(R.string.string_hintPermission));
    }

    @Override
    public void onCameraListener() {
        mWay = WAY_CAMREA;
        requestBasicPermission(mPermissions, REQUEST_CODE_PERMISSION);
    }

    @Override
    public void onAlbumListener() {
        mWay = WAY_ALBUM;
        requestBasicPermission(mPermissions, REQUEST_CODE_PERMISSION);
    }

    /**
     * 基本权限管理
     */
    private void requestBasicPermission(String[] permission, int requestCode) {
        MPermission.with(this)
                .addRequestCode(requestCode)
                .permissions(
                        permission
                ).request();
    }

    /**
     * 上传头像
     */
    public void upDataHead(File file) {
        RequestBody photoRequestBody = RequestBody.create(MediaType.parse(MultipartBody.FORM.toString()), file);
        MultipartBody.Part photoBody = MultipartBody.Part.createFormData("avatar_url", file.getName(), photoRequestBody);

        JsonApiWrapper.getApiService().userAvatar(setParams(), photoBody)
                .compose(new DefaultTransformer<CompanyBaseModel>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel>(this, true) {
                    @Override
                    public void onNext(CompanyBaseModel companyBaseModel) {
                        if (companyBaseModel.code == NetCode.HTTP_200) {
                            FileUtils.deleteTempFile();
                            ToastUtils.showToast("修改成功");
                            getUserInfo();
                        } else if (!TextUtils.isEmpty(companyBaseModel.msg)) {
                            ToastUtils.showToast(companyBaseModel.msg);
                        } else {
                            super.onNext(companyBaseModel);
                        }
                    }
                });
    }

    private HashMap<String, RequestBody> setParams() {
        HashMap<String, RequestBody> map = new HashMap<>();
        map.put("token", toRequestBody(SpUtils.getToken()));
        map.put("memberId", toRequestBody(SpUtils.getMemberId()));
        return map;
    }

    private RequestBody toRequestBody(String value) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), value);
        return requestBody;
    }

    /**
     * 得到的性别
     *
     * @param grnder
     */
    @Override
    public void onGrnderResult(String grnder) {
        viewDelegate.setGender(grnder);
        userGender();
    }

    /**
     * 修改性别
     */
    public void userGender() {
        JsonApiWrapper.getApiService().userGender(SpUtils.getToken(), viewDelegate.getGrnder())
                .compose(new DefaultTransformer<CompanyBaseModel>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel>(this, true) {
                    @Override
                    public void onNext(CompanyBaseModel companyBaseModel) {
                        if (companyBaseModel.code == NetCode.HTTP_200) {
                            ToastUtils.showToast(CodeUtils.getIdString(R.string.person_changeSuccess));
                        } else {
                            super.onNext(companyBaseModel);
                        }

                    }
                });
    }

    /**
     * 选择生日的回调
     *
     * @param calenderType
     * @param date
     */
    @Override
    public void onConfirm(int calenderType, String date) {
        viewDelegate.setBirthday(date);
        userBirthdate(calenderType);
    }

    /**
     * 修改生日
     *
     * @param calenderType
     */
    public void userBirthdate(int calenderType) {
        JsonApiWrapper.getApiService().userBirthdate(SpUtils.getToken(), calenderType, viewDelegate.getBirthday())
                .compose(new DefaultTransformer<CompanyBaseModel>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel>(this, true) {
                    @Override
                    public void onNext(CompanyBaseModel companyBaseModel) {
                        if (companyBaseModel.code == NetCode.HTTP_200) {
                            ToastUtils.showToast(CodeUtils.getIdString(R.string.person_changeSuccess));
                        } else {
                            super.onNext(companyBaseModel);
                        }
                    }
                });
    }
}
